import 'dart:async';
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chatbot/manager/dio_manager.dart';
import 'package:chatbot/model/base_model.dart';
import 'package:chatbot/model/completion_model.dart';
import 'package:chatbot/page/provider_example.dart';
import 'package:chatbot/page/vip_page.dart';
import 'package:chatbot/sse/sse_event_model.dart';
import 'package:chatbot/utils/colors.dart';
import 'package:chatbot/utils/utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/file.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:photo_view/photo_view.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

class CreatorImagePage extends StatefulWidget {
  final Creator creator;
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;

  const CreatorImagePage(
      {super.key,
      required this.creator,
      required this.speech,
      required this.speechProvider});

  @override
  State<StatefulWidget> createState() {
    return CreatorImageState(creator: creator);
  }
}

class CreatorImageState extends State<CreatorImagePage> {
  final Creator creator;
  final TextEditingController _textEditingController = TextEditingController();
  final ScrollController _controller = ScrollController();
  bool isSaving = false;

  CreatorImageState({required this.creator});

  bool showSaveButton = false;
  String menuTitle = "图片尺寸";
  String menuDefaultValue = "512x512";

  List<String> menuOptions = ["256x256", "512x512", "1024x1024"];

  var focusNode = FocusNode();
  String result = "";
  StreamController<SSEModel>? streamController;
  StreamTransformer<Uint8List, List<int>> unit8Transformer =
      StreamTransformer.fromHandlers(
    handleData: (data, sink) {
      sink.add(List<int>.from(data));
    },
  );
  bool isCreating = false;
  String prompt = "";

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ChatColors.lightColor,
      appBar: AppBar(
        backgroundColor: ChatColors.lightColor,
        leading: IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: const Icon(
              Icons.arrow_back_ios,
              color: Colors.black,
              size: 20,
            )),
        title: Text(
          creator.title,
          style: const TextStyle(
              color: Colors.black, fontSize: 16, fontWeight: FontWeight.w600),
        ),
      ),
      body: GestureDetector(
          onTap: () {
            focusNode.unfocus();
          },
          child: Stack(
            alignment: Alignment.topCenter,
            children: [
              SingleChildScrollView(
                controller: _controller,
                child: Column(
                  children: [
                    getDropMenu(menuTitle!, menuDefaultValue!, menuOptions,
                        (value) {
                      setState(() {
                        menuDefaultValue = value!;
                      });
                    }),
                    Container(
                      alignment: Alignment.centerLeft,
                      padding:
                          const EdgeInsets.only(left: 16, top: 16, bottom: 8),
                      child: const Text(
                        "图片描述",
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 15,
                            fontWeight: FontWeight.w600),
                      ),
                    ),
                    Container(
                      alignment: Alignment.center,
                      margin: const EdgeInsets.fromLTRB(16, 0, 16, 0),
                      height: MediaQuery.of(context).size.height / 5,
                      width: MediaQuery.of(context).size.width - 32,
                      decoration: BoxDecoration(
                        // color: ChatColors.commonLightColor,
                        color: ChatColors.darkTestColor,
                        borderRadius:
                            const BorderRadius.all(Radius.circular(12.0)),
                      ),
                      child: Stack(
                        alignment: Alignment.bottomRight,
                        children: [
                          TextField(
                            controller: _textEditingController,
                            style: const TextStyle(color: Colors.black),
                            keyboardType: TextInputType.text,
                            focusNode: focusNode,
                            maxLines: 6,
                            onChanged: (result) {
                              setState(() {
                                //更新发送按钮颜色
                              });
                            },
                            onSubmitted: (text) {
                              startCreate();
                            },
                            textInputAction: TextInputAction.done,
                            // textAlignVertical: TextAlignVertical.center,
                            decoration: InputDecoration(
                                contentPadding:
                                    const EdgeInsets.fromLTRB(8, 0, 8, 2),
                                border: InputBorder.none,
                                hintText: creator.example == ""
                                    ? "请详细描述你的要求，越详细，生成的图片越准确。"
                                    : creator.example,
                                hintStyle: const TextStyle(color: Colors.grey)),
                          ),
                          Positioned(
                            left: 2,
                            bottom: 1,
                            child: InkWell(
                              highlightColor: Colors.transparent, // 透明色
                              splashColor: Colors.transparent, //
                              onTap: () {
                                showModalBottomSheet(
                                  context: context,
                                  isDismissible: false,
                                  isScrollControlled: true,
                                  backgroundColor: ChatColors.lightColor,
                                  builder: (context) {
                                    return ProviderDemoApp(
                                      speech: widget.speech,
                                      speechProvider: widget.speechProvider,
                                      speechToTextCallBack: (String value) {
                                        _textEditingController.text = value;
                                        startCreate();
                                      },
                                    );
                                  },
                                );
                              },
                              child: Container(
                                  width: 26,
                                  height: 26,
                                  decoration: BoxDecoration(
                                    color: Colors.black.withOpacity(0.0),
                                    borderRadius: const BorderRadius.all(
                                        Radius.circular(22.0)),
                                  ),
                                  child: Icon(
                                    Icons.settings_voice,
                                    color: ChatColors.primaryColor,
                                    size: 20,
                                  )),
                            ),
                          ),
                          Positioned(
                            right: 8,
                            bottom: 3,
                            child: InkWell(
                                onTap: () {
                                  if (_textEditingController.text.isEmpty) {
                                    paste();
                                  } else {
                                    _textEditingController.text = "";
                                  }
                                  setState(() {});
                                },
                                highlightColor: Colors.transparent, // 透明色
                                splashColor: Colors.transparent, //
                                child: Text(
                                  _textEditingController.text.isEmpty
                                      ? "粘贴"
                                      : "清空",
                                  style: TextStyle(
                                      color: ChatColors.primaryColor.withOpacity(0.8),
                                      fontSize: 12,
                                      fontWeight: FontWeight.w600),
                                )),
                          ),
                        ],
                      ),
                    ),
                    result == ""
                        ? Container()
                        : Padding(
                            padding: const EdgeInsets.only(
                                left: 16, top: 36, right: 16),
                            child: Row(
                              children: [
                                const Text(
                                  "创作结果:",
                                  style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 14,
                                      fontWeight: FontWeight.w700),
                                ),
                                Expanded(child: Container()),
                                showSaveButton
                                    ? (isSaving
                                        ? CupertinoActivityIndicator(
                                            radius: 10.0,
                                            color: ChatColors.primaryColor)
                                        : InkWell(
                                            onTap: () {
                                              saveImage();
                                            },
                                            highlightColor:
                                                Colors.transparent, // 透明色
                                            splashColor: Colors.transparent, //
                                            child: Text(
                                              "保存",
                                              style: TextStyle(
                                                  color:
                                                      ChatColors.primaryColor,
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w700),
                                            )))
                                    : Container(),
                              ],
                            ),
                          ),
                    result == ""
                        ? Container()
                        : Padding(
                            padding: EdgeInsets.only(
                                left: 16,
                                top: 12,
                                right: 16,
                                bottom:
                                    MediaQuery.of(context).padding.bottom + 90),
                            child: SizedBox(
                              width: MediaQuery.of(context).size.width - 32,
                              height: MediaQuery.of(context).size.width - 32,
                              child: PhotoView(
                                imageProvider: CachedNetworkImageProvider(
                                  result,
                                ),
                                loadingBuilder: (context, event) {
                                  if (event != null) {
                                    showSaveButton =
                                        event.cumulativeBytesLoaded ==
                                            event.expectedTotalBytes!;
                                    debugPrint(
                                        "event.cumulativeBytesLoaded=${event.cumulativeBytesLoaded}  event.expectedTotalBytes!=${event.expectedTotalBytes!}");
                                    Future.delayed(
                                        const Duration(milliseconds: 500), () {
                                      if (showSaveButton && mounted) {
                                        setState(() {});
                                      }
                                    });
                                  }
                                  return Center(
                                    child: SizedBox(
                                        width: 120.0,
                                        height: 4.0,
                                        child: LinearProgressIndicator(
                                          value: event == null
                                              ? 0
                                              : event.cumulativeBytesLoaded /
                                                  event.expectedTotalBytes!,
                                          color: ChatColors.primaryColor,
                                          //<-- SEE HERE
                                          backgroundColor:
                                              Colors.grey, //<-- SEE HERE
                                        )),
                                  );
                                },
                              ),
                            ),
                          ),
                  ],
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: Container()),
                  const Padding(
                    padding: EdgeInsets.only(bottom: 6.0),
                    child: Text(
                      "图片绘制可能需要一些时间，请耐心等待",
                      style: TextStyle(
                          color: Colors.grey,
                          fontSize: 10,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                  InkWell(
                    highlightColor: Colors.transparent, // 透明色
                    splashColor: Colors.transparent, //
                    onTap: () {
                      startCreate();
                    },
                    child: Container(
                        alignment: Alignment.center,
                        width: MediaQuery.of(context).size.width - 72,
                        height: 40,
                        margin: EdgeInsets.only(
                            bottom: 24 + MediaQuery.of(context).padding.bottom),
                        decoration: BoxDecoration(
                          color: isCreating
                              ? ChatColors.darkColor
                              : ChatColors.primaryColor,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(8.0)),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            isCreating
                                ? Padding(
                                    padding: const EdgeInsets.only(right: 8.0),
                                    child: CupertinoActivityIndicator(
                                        radius: 10.0,
                                        color: ChatColors.primaryColor),
                                  )
                                : Container(),
                            Text(
                              isCreating ? "停止绘画" : "开始绘画",
                              style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                  fontWeight: FontWeight.w600),
                            ),
                          ],
                        )),
                  ),
                ],
              )
            ],
          )),
    );
  }

  startCreate() async {
    if (isCreating) {
      isCreating = false;
      if (mounted) {
        setState(() {});
      }
    } else {
      if (_textEditingController.text != "") {
        focusNode.unfocus();
        result = "";
        prompt = creator.prompt;
        // if (menuDefaultValue != null) {
        //   prompt = prompt.replaceAll("{1}", menuDefaultValue!);
        // }

        isCreating = true;
        if (mounted) {
          setState(() {});
        }

        try {
          Response response = await DioManager.instance.dio.post(
            "chatgpt/imageCreator",
            data: {
              "size": menuDefaultValue,
              "prompt": _textEditingController.text
            },
          );
          Map resultMap = response.data;
          debugPrint('image response：${response.data.toString()}');
          if (resultMap.containsKey('code') && resultMap['code'] == 200) {
            BaseModel creatorEntity =
                BaseModel.fromMap(resultMap as Map<String, dynamic>);

            if (creatorEntity.message.isNotEmpty) {
              _textEditingController.text = "";
              result = creatorEntity.message;
              debugPrint("result==$result");
              isCreating = false;
              // Utils.showToast("绘制完成，加载中...");
              if (mounted) {
                setState(() {});
              }
            }
          }
        } catch (e) {
          isCreating = false;
          if (mounted) {
            setState(() {});
          }
          return null;
        }

        // startSSE(prompt);
      } else {
        Utils.showToast("请填写提示词");
      }
    }
  }

  void scrollBottom() {
    _controller.animateTo(
      _controller.position.maxScrollExtent,
      duration: const Duration(milliseconds: 500),
      curve: Curves.linear,
    );
  }

  /// 获取内容
  paste() async {
    var clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
    if (mounted) {
      setState(() {
        _textEditingController.text = clipboardData?.text ?? '';
      });
    }
  }

  getDropMenu(String title, String dropdownValue, List<String> items,
      DropMenuCallBack callBack) {
    debugPrint(
        "title=$title,dropdownValue=$dropdownValue,size=${items.length}");
    return Container(
      width: MediaQuery.of(context).size.width - 32,
      height: 42,
      padding: const EdgeInsets.only(left: 12, right: 12),
      margin: const EdgeInsets.only(top: 12),
      decoration: BoxDecoration(
        border: Border.all(
            color: ChatColors.darkColor.withOpacity(0.4), width: 1),
        borderRadius: const BorderRadius.all(Radius.circular(4.0)),
      ),
      child: Row(
        children: [
          Text(
            title,
            style: const TextStyle(
                color: Colors.black, fontSize: 15, fontWeight: FontWeight.w500),
          ),
          Expanded(child: Container()),
          DropdownButton<String>(
            underline: Container(),
            dropdownColor: ChatColors.darkTestColor,
            style: const TextStyle(
                color: Colors.black, fontSize: 15, fontWeight: FontWeight.w500),
            value: dropdownValue,
            onChanged: (String? newValue) {
              if (newValue != null) {
                callBack(newValue);
              }
            },
            items: items.map<DropdownMenuItem<String>>((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  void saveImage() async {
    if (mounted) {
      setState(() {
        isSaving = true;
      });
    }
    File file = await DefaultCacheManager().getSingleFile(result);
    final savedResult = await ImageGallerySaver.saveFile(file.path);
    if (mounted) {
      setState(() {
        isSaving = false;
      });
    }
    Utils.showToast("保存成功");
  }
}

typedef DropMenuCallBack = void Function(String? value);
